<template>
  <el-card shadow="never" class="table-container">
    <div class="app-container">
      <div class="titleMolde">设备管理
      </div>
      <el-tabs type="border-card" v-model="queryParams.status" @tab-change="handleQuery">
        <el-tab-pane label="未分配" :name="2">
          <div class="Filters">
            <el-input v-model="queryParams.key" style="width: 200px" placeholder="设备IMEI号/设备编号(BT码)" />
            <!-- <el-select v-model="queryParams.status" placeholder="请选择分配" style="width: 200px">
              <el-option v-for="(item, idx) in statusOption" :key="idx" :label="item.label" :value="item.value" />
            </el-select> -->
            <el-button type="primary" class="mrg-lf-10" @click="handleQuery">查询</el-button>
            <el-button type="primary" class="mrg-lf-10" @click="addPageQuery()"
              v-hasPerm="['Device:add']">添加</el-button>
            <el-button type="primary" class="mrg-lf-10" @click="distributeDevice"
              v-hasPerm="['Device:assignment']">分配设备</el-button>
            <el-upload action="" :on-change="handleChange" class="mrg-lf-10"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              :auto-upload="false" :show-file-list="false">
              <el-button v-loading.fullscreen.lock="fullscreenLoading" type="primary"
                v-hasPerm="['Device:Bulkimport']">批量导入</el-button>
            </el-upload>
            <el-button type="primary" @click="exportExcel" class="mrg-lf-10">
              模板下载
            </el-button>
          </div>
          <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="设备IMEI号" align="center" prop="deviceCode" />
            <el-table-column label="设备编号(BT码)" align="center" prop="towerNumber" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="设备类型名称" align="center" prop="deviceTypeName" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" align="center" fixed="right" width="220">
              <template #default="scope">
                <el-button title="编辑" v-hasPerm="['Device:edit']" type="primary" icon="edit" circle
                  @click.prevent="addPageQuery(scope.row)" />
                <el-button title="删除" v-hasPerm="['Device:delete']" type="danger" icon="delete" circle
                  @click.prevent="deleteRow(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <pagination @pagination="handleQuery" v-if="queryParams.pages.total > 0"
            v-model:total="queryParams.pages.total" v-model:page="queryParams.pages.current"
            v-model:limit="queryParams.pages.size" />
        </el-tab-pane>
        <el-tab-pane label="已分配" :name="1">
          <div class="Filters">
            <el-input v-model="queryParams.key" style="width: 200px" placeholder="设备IMEI号/设备编号(BT码)" />
            <el-button type="primary" class="mrg-lf-10" @click="handleQuery">查询</el-button>
            <el-button type="primary" class="mrg-lf-10" @click="addPageQuery()">添加</el-button>
            <el-button type="primary" class="mrg-lf-10" @click="distributeDevice">分配设备</el-button>
          </div>
          <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="设备IMEI号" align="center" prop="deviceCode" />
            <el-table-column label="设备编号(BT码)" align="center" prop="towerNumber" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="设备类型名称" align="center" prop="deviceTypeName" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" align="center" fixed="right" width="220">
              <template #default="scope">
                <el-button title="编辑" type="primary" icon="edit" circle @click.prevent="addPageQuery(scope.row)" />
                <el-button title="删除" type="danger" icon="delete" circle @click.prevent="deleteRow(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <pagination @pagination="handleQuery" v-if="queryParams.pages.total > 0"
            v-model:total="queryParams.pages.total" v-model:page="queryParams.pages.current"
            v-model:limit="queryParams.pages.size" />
        </el-tab-pane>

      </el-tabs>

    </div>
  </el-card>

  <el-dialog destroy-on-close class="dialogTableVisibleclass" v-model="outerVisible" :title="dialog"
    @close="handleCloseDialog">
    <div class="div-container fontColor_333">
      <el-form ref="AddruleFormRef" :rules="rules" :model="addDeviceType" label-width="auto" style="width: 600px"
        class="form-container">
        <el-form-item label="设备IMEI号" prop="deviceCode">
          <el-input v-model="addDeviceType.deviceCode" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="addDeviceType.deviceName" />
        </el-form-item>
        <!-- <el-form-item label="设备类型" prop="deviceTypeId">
          <el-select v-model="addDeviceType.deviceTypeId" @change="changedeviceTypeId" placeholder="请选择设备类型"
            size="large">
            <el-option v-for="(item, idx) in options" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModelId">
          <el-select v-model="addDeviceType.deviceModelId" placeholder="请选择设备型号" size="large">
            <el-option v-for="item in options2" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备规格" prop="deviceSpecId">
          <el-select v-model="addDeviceType.deviceSpecId" placeholder="请选择设备规格" size="large">
            <el-option v-for="item in options3" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="设备编号(BT码)" prop="towerNumber">
          <el-input v-model="addDeviceType.towerNumber" />
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-input v-model="addDeviceType.module" />
        </el-form-item>
        <el-form-item label="软件" prop="softVer">
          <el-input v-model="addDeviceType.softVer" />
        </el-form-item>
        <el-form-item label="硬件" prop="hardVer">
          <el-input v-model="addDeviceType.hardVer" />
        </el-form-item>
        <el-form-item label="IMEI" prop="IMEI">
          <el-input v-model="addDeviceType.IMEI" />
        </el-form-item>
        <el-form-item label="ICCID" prop="ICCID">
          <el-input v-model="addDeviceType.ICCID" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="outerVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSave">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog destroy-on-close class="dialogTableVisibleclass" v-model="outerVisibleDistribute" title="分配设备">
    <div class="div-container fontColor_333">
      <el-cascader style="width: 500px" ref="cascader" :options="projectDATA"
        :props="{ label: 'customerName', value: 'id', checkStrictly: true }" placeholder="请选择客户" clearable
        @change="selectchange"></el-cascader>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="outerVisibleDistribute = false">关闭</el-button>
        <el-button type="primary" @click="Devicedistribute">分配</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import DeviceApi, { FencesPageQuery, DeviceTypeReq } from "@/api/device";
import DeviceTypeApi, { deviceTypePageQueryList } from "@/api/deviceType";
import deviceModelApi, { deviceModelPageQuery } from "@/api/deviceModel";
import DeviceSpecApi, { deviceSpecPageQuery } from "@/api/deviceSpec";
import CustomerAPI from "@/api/customer";
import * as XLSX from 'xlsx'


import type { FormInstance, FormRules } from 'element-plus'
const AddruleFormRef = ref(ElForm)
const EditruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules<DeviceTypeReq>>({
  deviceCode: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
  // deviceTypeId: [
  //   { required: true, message: '请选择设备类型', trigger: 'blur' },
  // ],
  // deviceModelId: [
  //   { required: true, message: '请选择型号', trigger: 'blur' },
  // ],
  // deviceSpecId: [
  //   { required: true, message: '请选择规格', trigger: 'blur' },
  // ],
})

/**
@date: 2024-09-06 17:52:45
选择的设备
*/
let multipleSelection = ref([{ id: '' }])
let projectDATA = ref()
let cascaderVlaue = ref("")
/** 分页查询参数  */
let deviceSpecList = reactive<deviceSpecPageQuery>({
  "pages": {
    "current": 1,
    "size": 99999,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "name": "",
});
/** 分页查询参数  */
let deviceModelList = reactive<deviceModelPageQuery>({
  "pages": {
    "current": 1,
    "size": 99999,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "name": "",
});
/** 分页查询参数  */
let deviceTypeList = reactive<deviceTypePageQueryList>({
  "pages": {
    "current": 1,
    "size": 99999,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "typeName": "",
  "customerId": 0,
});
let statusOption = ref([
  {
    "value": 0,
    "label": "全部"
  },
  {
    "value": 1,
    "label": "已分配"
  },
  {
    "value": 2,
    "label": "未分配"
  }
])
let options = ref([
  {
    "id": "1831172940171685889",
    "creatorId": "1",
    "createTime": "2024-09-04 11:30:25.000",
    "typeName": "啊榆",
    "typeCode": "",
    "enableFlag": "ENABLE",
    "remark": "测试123"
  }
])
let options2 = ref([
  {
    "id": "1820396174301822978",
    "creatorId": "1",
    "createTime": "2024-08-05 17:47:24.000",
    "name": "test3",
    "customerId": 0,
    "customerName": "集智云BMS"
  }
])
let options3 = ref([
  {
    "id": "1831538229996507137",
    "creatorId": "1",
    "createTime": "2024-09-05 11:41:57.000",
    "name": "测试1",
    "customerId": 0,
    "customerName": "集智云BMS"
  }
])
/**
@date: 2024-08-31 14:55:16
新增设备
*/
let outerVisible = ref(false);
let dialog = ref('');
/**
@date: 2024-08-31 14:55:01
编辑设备
*/
let outerVisibleEdit = ref(false);
let outerVisibleDistribute = ref(false);
const loading = ref(false);
let pageData = ref()
/** 分页查询参数  */
let queryParams = reactive<FencesPageQuery>({
  "pages": {
    "current": 1,
    "size": 10,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "status": 2,
  "key": undefined,
  "deviceType": undefined,
});
let addDeviceType = reactive<DeviceTypeReq>({
});
let editDeviceType = reactive<DeviceTypeReq>({
  deviceName: "",
  "deviceCode": "",
  // "deviceTypeId": "",
  "module": "",
  "softVer": "",
  "hardVer": "",
  "status": 1,
  // "deviceModelId": "",
  // "deviceSpecId": "",
  "towerNumber": "",

  "IMEI": "",
  "ICCID": ""
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  queryParams.status = queryParams.status === 1 ? undefined : queryParams.status;
  DeviceApi.getFences(queryParams)
    .then((data) => {
      pageData.value = data.records;
      queryParams.pages.total = data.total;
      queryParams.pages.current = data.current;
      console.log('分页', data);
    })
    .finally(() => {
      loading.value = false;
    });
}
/**
@date: 2024-09-06 18:04:10
添加设备弹窗
*/
function addPageQuery(data?: any) {
  console.log(data, '0000');

  outerVisible.value = true
  DeviceTypeQuery()
  deviceModelQuery()
  deviceSpecQuery()
  if (data) {
    dialog.value = "修改设备";
    nextTick(() => {
      const { createTime, ...rest } = data;
      let id = data.id
      // Object.assign(addDeviceType, rest);
      DeviceApi.getdeviceID(id).then((res) => {
        Object.assign(addDeviceType, res);

      })

    })
  } else {
    dialog.value = "新增设备";
  }
}


function changedeviceTypeId(value: any) {
  console.log(value, '---', addDeviceType);

}
/** 关闭弹窗 */
function handleCloseDialog() {
  addDeviceType = reactive<DeviceTypeReq>({})
  outerVisible.value = false;
  AddruleFormRef.value.resetFields();
  AddruleFormRef.value.clearValidate();
}

const addSave = useThrottleFn(() => {
  AddruleFormRef.value.validate((valid: any) => {
    if (valid) {
      if (dialog.value === '修改用户') {
        DeviceApi.editSave(addDeviceType)
          .then((data) => {
            handleQuery();
            ElMessage.success('编辑成功');
          })
          .finally(() => {
            outerVisible.value = false

          });
      } else {
        DeviceApi.addDevType(addDeviceType)
          .then((data) => {
            console.log(data);
            handleQuery();
            ElMessage.success('添加成功');
          })
          .finally(() => {
            outerVisible.value = false
          });
      }
    }
  });
})

function editRow(datas: any) {
  outerVisibleEdit.value = true
  editDeviceType.id = datas.id
  // editDeviceType.name = datas.name
  // editDeviceType.customerId = datas.customerId
}
/**
@date: 2024-08-31 14:23:01
编辑设备
*/
const editSave = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      DeviceApi.editSave(editDeviceType)
        .then((data) => {
          handleQuery();
          ElMessage.success('编辑成功');
          outerVisibleEdit.value = false
        })
        .finally(() => {
          outerVisibleEdit.value = false

        });
    } else {
      console.log('error submit!', fields)
    }
  })
}
/**
@date: 2024-08-31 14:22:46
删除设备
*/
function deleteRow(datas: any) {
  DeviceApi.deleteSave(datas.id)
    .then((data) => {
      console.log('添加', data);
      handleQuery();
      ElMessage.success('删除成功');
    })
    .finally(() => {
    });
}
/** 查询设备类型 */
function DeviceTypeQuery() {
  DeviceTypeApi.getFences(deviceTypeList)
    .then((data) => {
      options.value = data.records;
      deviceTypeList.pages.total = data.total;
      deviceTypeList.pages.current = data.current;
    })
    .finally(() => {
    });
}
/** 查询型号 */
function deviceModelQuery() {
  loading.value = true;
  deviceModelApi.getFences(deviceModelList)
    .then((data) => {
      options2.value = data.records;
      deviceModelList.pages.total = data.total;
      deviceModelList.pages.current = data.current;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 查询规格 */
function deviceSpecQuery() {
  loading.value = true;
  DeviceSpecApi.getFences(deviceSpecList)
    .then((data) => {
      options3.value = data.records;
      deviceSpecList.pages.total = data.total;
      deviceSpecList.pages.current = data.current;
      console.log('分页', data);
    })
    .finally(() => {
      loading.value = false;
    });
}
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
function distributeDevice() {
  outerVisibleDistribute.value = true
  CustomerAPI.getCustomerTree().then((data: any) => {
    projectDATA.value = []
    projectDATA.value.push(data)
    console.log('树', data);
  });
}
function selectchange(e: any) {
  if (e) {
    cascaderVlaue.value = e[e.length - 1]

  } else {
    cascaderVlaue.value = ""

  }
}
function Devicedistribute() {
  if (cascaderVlaue.value) {
    var data = {
      deviceId: [] as any,
      customerId: cascaderVlaue.value,
    }
    multipleSelection.value.forEach((item: any) => {
      data.deviceId.push(item.id)
    })
    console.log(data);

    DeviceApi.BatchAllocate(data)
      .then(() => {
        handleQuery();
        ElMessage.success('分配成功');
        outerVisibleDistribute.value = false
      })
      .finally(() => {
        outerVisibleEdit.value = false

      });
  } else {
    ElMessage.warning('请选择项目');
  }
}

let fullscreenLoading = ref(false)
function handleChange(file: any) {
  console.log(file.raw.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  if (file.raw) {
    if ((file.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") || (file.raw.type === 'application/vnd.ms-excel')) {
      handleUpload(file)
    } else {
      ElMessage({
        message: '文件有误',
        type: 'warning'
      })
    }
  } else {
    ElMessage({
      message: '文件有误',
      type: 'warning'
    })
  }
}

//读取excel文件
const readFile = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsArrayBuffer(file.raw)
    reader.onload = (e: any) => {
      resolve(e.target.result)
    }
    reader.onerror = (e) => {
      reject(e)
    }
  })
}

const handleUpload = async (file: any) => {
  const data = await getXlsxData(file);
  console.log(data);

  const arr = ref<DeviceTypeReq[]>([]); // 使用 ref 而不是 reactive
  data.forEach((v: any) => {
    const obj = {
      deviceName: v['设备名称'],
      deviceCode: v['设备IMEI号'],
      towerNumber: v['设备编号(BT码)'],
      module: v['模块'],
      softVer: v['软件'],
      hardVer: v['硬件'],
      IMEI: v['IMEI'],
      ICCID: v['ICCID']
    };
    console.log(obj);
    arr.value.push(obj); // 通过 arr.value 来访问和更新
  });
  let i = 0
  for (const item of arr.value) {
    try {
      await BatchaddDev(item); // 等待每个项上传完成
      i++
      console.log();
      if (i === arr.value.length) {
        handleQuery();
        ElMessage.success('上传成功');
      }

    } catch (error) {
      console.error('上传失败:', error);
      // 处理错误，比如可以选择是否继续上传后续项
    }
  }
};

async function BatchaddDev(data: DeviceTypeReq) {
  return DeviceApi.addDevType(data);
}
//读取表格数据
const getXlsxData = async (file: any) => {
  const dataBinary = await readFile(file)
  console.log(dataBinary);

  const workBook = XLSX.read(dataBinary)
  console.log(workBook);

  const workSheet = workBook.Sheets[workBook.SheetNames[0]]
  console.log(workSheet);

  const data = XLSX.utils.sheet_to_json(workSheet)
  console.log(data);

  return data
}
// 下载升级模板
function exportExcel() {
  let header = ['设备IMEI号', '设备名称', '模块', '软件', '硬件', '设备编号(BT码)', 'IMEI', 'ICCID']
  let datas = [
    ['BT104453010', '换电']
  ]
  import('@/vendor/Export2Excel').then(async excel => {
    excel.export_json_to_excel({
      // @ts-ignore
      header: header, // 表头 必填
      data: datas, // 具体数据 必填
      filename: '上传设备模板', // 文件名称
      autoWidth: true, // 宽度是否自适应
      bookType: 'xlsx' // 生成的文件类型
    })
  })
}
onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
.mrg-lf-10 {
  margin-left: 10px;
}

.fontColor_333 {
  :deep(.el-input__inner) {
    color: #333;
  }

  :deep(.el-select__selected-item) {
    span {
      color: #333;
    }
  }

}

.titleMolde {
  font-weight: bold;
  position: relative;
  display: flex;
  padding-left: 15px;
  justify-content: space-between;
  align-items: center;

  &::after {
    content: "";
    width: 8px;
    height: 8px;
    position: absolute;
    left: 4px;
    top: 6px;
    background: #2cdfe5b5;
  }

  &::before {
    content: "";
    width: 8px;
    height: 8px;
    background: #09e0e7;
    position: absolute;
    left: 0;
    top: 2px;
  }

}

.app-container {
  position: relative;
  padding: 10px;


  .allTabContent {
    display: flex;
    align-items: center;
    position: absolute;
    top: 15px;
    right: 0;

    div {
      margin-left: 26px;
      font-weight: 700;

      span {
        margin-left: 8px;
      }
    }
  }
}

.Filters {
  margin: 10px 0;
  display: flex;
  align-items: center;

  .el-segmented {
    --el-segmented-item-selected-color: var(--el-text-color-primary);
    --el-segmented-item-selected-bg-color: #5cadff;
    --el-border-radius-base: 16px;
  }

  &>div {
    margin-right: 5px;
  }
}

.div-container {
  display: flex;
  width: 100%;
  color: #333;

  .div-left-container {
    width: 420px;

    .div_search {}
  }

  .div-right-container {
    width: calc(100% - 420px - 10px);
    margin-left: 10px;
    position: relative;

    #myPageTop {
      position: absolute;
      top: 60px;
      left: 10px;
      z-index: 6;
      background-color: #fff;
      border: 1px solid #ccc;
      padding: 10px;

      #tipinput {
        background-color: #fff;
        color: #333;
        border: 1px solid #ccc;
        padding: 5px;
      }
    }
  }

  :deep(.form-container) {
    .el-form-item__label {
      color: #333;
    }

    .el-input__inner {
      color: #333;
    }

    .el-textarea__inner {
      color: #333;

    }
  }
}
</style>
<style>
.amap-sug-result {
  z-index: 9999 !important;
  color: #333
}
</style>
